package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.result.ResultCodeEnum;
import com.atguigu.yygh.common.utils.MD5;
import com.atguigu.yygh.hosp.repository.HospitalRepository;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.hosp.service.HospitalSetService;
import com.atguigu.yygh.model.hosp.Hospital;
import exception.YyghException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: Ricard Tang
 * @Date: 2022/10/24/15:47
 * @Description:
 */
@Service
public class HospitalServiceImpl implements HospitalService {
    @Autowired
    private HospitalRepository hospitalRepository;
    @Autowired
    private HospitalSetService hospitalSetService;

    @Override
    public void saveHosp(Map<String, Object> paramMap) {
        //获取传递的医院签名 -- 经过MD5加密
        String hospSign = (String) paramMap.get("sign");
        //把map集合转换为对象
        String mapString = JSONObject.toJSONString(paramMap);
        Hospital hospital = JSONObject.parseObject(mapString, Hospital.class);
        String hoscode = hospital.getHoscode();

        //验证签名是否一致
        checkSign(hospSign,hoscode);

        //处理图片 传输过程中"+"转换为" " ,所以需要转换回来
        String logoData = hospital.getLogoData().replace(" ","+");
        hospital.setLogoData(logoData);
        //判断是否存在相同的数据
        Hospital hospitalExist = hospitalRepository.getHospitalByHoscode(hoscode);
        if (hospitalExist != null){
            //存在，进行修改
            hospital.setStatus(hospitalExist.getStatus());
            hospital.setCreateTime(hospitalExist.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        }else {
            //0：未上线 1：已上线
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        }
    }

    @Override
    public Hospital getByHoscode(String hoscode) {
        return hospitalRepository.getHospitalByHoscode(hoscode);
    }

    /**
     * 验证签名是否一致
     * @param hospSign
     * @param hoscode
     */
    private void checkSign(String hospSign ,String hoscode){
        //根据传递过来的医院编码，查询数据库，查询签名
        String signKey = hospitalSetService.getSignKey(hoscode);
        //数据库中不存在该signKey
        if (signKey == null)
            throw new YyghException(ResultCodeEnum.SIGN_ERROR);

        //判断签名是否一致
        String signKeyMd5 = MD5.encrypt(signKey);
        if (!hospSign.equals(signKeyMd5))
            throw new YyghException(ResultCodeEnum.SIGN_ERROR);
    }
}
